<?php


namespace api\zmt\controller;


use api\zmt\model\payModel;
use api\zmt\model\RegistrationModel;
use api\zmt\validate\PayValidate;
use cmf\controller\RestBaseController;
use Firebase\JWT\JWT;
use think\facade\Db;
use think\Request;

class payinfoController extends RestBaseController
{
    public function index(Request $request){
        if (request()->isPost()){
            $data  = request()->post();
            $validate = new PayValidate();
            if (!$validate->scene('pay')->check($data)){
                return json(['code'=>'0','msg'=>$validate->getError(),'data'=>null]);
            }
            $primarmoney = RegistrationModel::find($request->userId);

            $pay = [
                'user_id' => $request->userId,
                'money' => $data['money'],
                'reason' => $data['reason']??'充值',
                'before' => $primarmoney['wallet'],
                'after' => $primarmoney['wallet'] + $data['money'],
                'type' => 1,
                'create_time' => date('Y-m-d H:i:s'),
            ];

            //开启事务
            Db::startTrans();
            //作用域
            $wallte = false;
            $payModel = false;
            try{
                //记账流水
                $payModel = payModel::create($pay);
                $wallte = RegistrationModel::where('id',$request->userId)->update(['wallet'=>$pay['after']]);

            }catch (\Exception $exception){
                Db::rollback();
                return json(['status'=>'success','message'=>$exception->getMessage()],500);
            }
            if ($wallte && $payModel){
                Db::commit();
                return json(['status'=>'success','message'=>'充值成功','data'=>'你的充值金额是￥'.$data['money'].'充值明细为：'.$payModel]);
            }else{
                Db::rollback();
                return json(['code'=>'0','msg'=>'充值失败']);
            }
        }
    }

    public function selectPay(Request $request){
        try{
            $check = payModel::where('user_id',$request->userId)->order('create_time','desc')->select();
            return json(['status'=>'success','data'=>$check]);
        }catch (\Exception $exception){}
        return json(['status'=>'success','message'=>$exception->getMessage()],500);
    }
}